package com.wh.typeLock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁------lock
 */
public class LockDemo2 {
    public static void main(String[] args) {
        Phone2 phone = new Phone2();
        new Thread(() -> {
            phone.sendSms();
        }, "A").start();
        new Thread(() -> {
            phone.sendSms();
        }, "B").start();

    }
}

class Phone2 {
    Lock lock = new ReentrantLock();

    public void sendSms() {//当前25行
        lock.lock(); //细节问题 26行和34行的lock unlock是一对 26行进来，会拿到2个锁（会把call的锁也拿到）
        //锁必须配对，否则就会死锁（例如：2个lock,1个unlock，就会死锁）
        try {
            System.out.println(Thread.currentThread().getName() + "-->Sms");
            call(); //这里也有锁
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void call() {//当前38行
        lock.lock(); //39 和45是一对
        try {
            System.out.println(Thread.currentThread().getName() + "-->call");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}